package org.shean.app.rssreader;

import java.util.ArrayList;

import org.shean.app.rssreader.provider.SzRSSReader;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Contacts;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AutoCompleteTextView;
import android.widget.CursorAdapter;
import android.widget.Filterable;
import android.widget.LinearLayout;
import android.widget.TextView;

public class EditTagActivity extends Activity implements View.OnClickListener{
	private LayoutInflater mInflater;
	private ArrayList<View> mTagViewList;
	private LinearLayout mTagGroup = null;
	private int mDeleteViewNum = 0;
	private static final int MAX_DELETE_NUMBER = 5;
	private int mType = -1;
	private long mPostID;
	
	private static final int EDIT_COMMENT = 1;
	private static final int EDIT_TAG = 2;
	
	private  ContactListAdapter mAdapter;
	
	@Override
	protected void onCreate(Bundle icicle) {
		super.onCreate(icicle);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		//mInflater = getLayoutInflater();
		//mLinear = new LinearLayout(this);
		//mLinear.setOrientation(LinearLayout.VERTICAL);
		setContentView(R.layout.edit_separator_alone);
		getWindow().setLayout(WindowManager.LayoutParams.FILL_PARENT,
                WindowManager.LayoutParams.WRAP_CONTENT);
		
		mTagGroup = (LinearLayout)this.findViewById(R.id.tag_group);
		mInflater = getLayoutInflater();
		TextView text = (TextView) findViewById(R.id.text);
		
		if(this.getIntent().getAction().equals("android.intent.action.EDIT_TAG"))
		{
			text.setText("Tag");
			mType = EDIT_TAG;
		}
		else if(this.getIntent().getAction().equals("android.intent.action.EDIT_COMMENT"))
		{
			text.setText("Comment");
			mType = EDIT_COMMENT;
		}

		View addbtn = findViewById(R.id.add);
		addbtn.setOnClickListener(this);
		
		View cancelbtn = findViewById(R.id.cancel);
		cancelbtn.setOnClickListener(this);
		
		View editbtn = findViewById(R.id.edit);
		editbtn.setOnClickListener(this);
		
		mTagViewList = new ArrayList<View>();
		
		mPostID = Long.parseLong(getIntent().getData().getPathSegments().get(1));
		
		ContentResolver content = getContentResolver();
        Cursor cursor = content.query(SzRSSReader.Tags.CONTENT_URI,
        		TAG_PROJECTION, null, null, SzRSSReader.Tags.DEFAULT_SORT_ORDER);
        mAdapter = new ContactListAdapter(this, cursor);
		
		if(mType == EDIT_TAG)
			initTagView();
		else if(mType ==  EDIT_COMMENT)
			initCommentView();
	}
	
	@Override
	protected void onDestroy()
	{
		mTagViewList.clear();
		super.onDestroy();
	}


	public void onClick(View v) {
		switch(v.getId())
		{
		case R.id.add:
			View view = mInflater.inflate(R.layout.edit_contact_entry, mTagGroup, false);
			View deletebtn = view.findViewById(R.id.delete);
			TextView commenttext = (TextView)view.findViewById(R.id.comment_data);
			AutoCompleteTextView tagView = (AutoCompleteTextView)view.findViewById(R.id.tag_data);
			switch(mType)
			{
			case EDIT_COMMENT:
				commenttext.setVisibility(View.VISIBLE);
				tagView.setVisibility(View.GONE);
				break;
			case EDIT_TAG:
				tagView.setVisibility(View.VISIBLE);
				commenttext.setVisibility(View.GONE);
				tagView.setAdapter(mAdapter);
				break;
			}
			deletebtn.setOnClickListener(this);
			
			PostTagViewTag viewtag = new PostTagViewTag();
			viewtag.is_new = true;
			
			view.setTag(viewtag);
			
			mTagViewList.add(view);
			buildView();
			return;
		case R.id.delete:
			View parent = (View)v.getParent();
			parent.setVisibility(View.GONE);
			
			mDeleteViewNum ++ ;
			if(mDeleteViewNum > MAX_DELETE_NUMBER)
				clearDeleteView();
			return;
		case R.id.edit:
			if(mType == EDIT_TAG)
				insertTags();
			else if(mType == EDIT_COMMENT)
				insertComments();
			
			setResult(RESULT_OK);
		case R.id.cancel:
			finish();
			return;
		}
	}
	
	private void insertComments()
	{
		for(int i = 0; i < mTagViewList.size() ; i++)
		{
			View view = mTagViewList.get(i);
			if(view.getVisibility() == View.VISIBLE)
			{
				TextView commenttext = (TextView)view.findViewById(R.id.comment_data);
				String comment = commenttext.getText().toString();
				if(comment != null && comment.length() > 0)
				{
					PostTagViewTag viewtag = (PostTagViewTag)view.getTag();
					if(!viewtag.is_new)
					{
						if(viewtag.old_text.equals(comment))
							continue;
						else
						{
							ContentValues value = new ContentValues();
							value.put(SzRSSReader.PostComments.COMMENT, comment);
							this.getContentResolver().update(SzRSSReader.PostComments.CONTENT_URI, value, 
									SzRSSReader.PostComments._ID + "='" + viewtag._id + "'", null);
						}
					}
					else
					{
						ContentValues value = new ContentValues();
						value.put(SzRSSReader.PostComments.POST_ID, mPostID);
						value.put(SzRSSReader.PostComments.COMMENT, comment);
						this.getContentResolver().insert(SzRSSReader.PostComments.CONTENT_URI, value);
					}
				}
			}
			else
			{
				PostTagViewTag viewtag = (PostTagViewTag)view.getTag();
				if(!viewtag.is_new)
				{
					String where = SzRSSReader.PostComments._ID + "='" + viewtag._id + "'";
					this.getContentResolver().delete(SzRSSReader.PostComments.CONTENT_URI, where, null);
				}
			}
		}
	}
	
	
	private void insertTags()
	{
		for(int i = 0; i < mTagViewList.size() ; i++)
		{
			View view = mTagViewList.get(i);
			if(view.getVisibility() == View.VISIBLE)
			{
				AutoCompleteTextView tagView = (AutoCompleteTextView)view.findViewById(R.id.tag_data);
				String tag = tagView.getText().toString();
				if(tag != null && tag.length() > 0)
				{
					PostTagViewTag viewtag = (PostTagViewTag)view.getTag();
					if(!viewtag.is_new)
					{
						if(viewtag.old_text.equals(tag))
							continue;
						else
						{
							String where = SzRSSReader.PostTags.TAG_ID + "='" + viewtag._id + "' AND "
										+ SzRSSReader.PostTags.POST_ID + "='" + mPostID + "'";
							this.getContentResolver().delete(SzRSSReader.PostTags.CONTENT_URI, where, null);
						}
					}
					ContentValues value = new ContentValues();
					value.put(SzRSSReader.PostTags.POST_ID, mPostID);
					value.put(SzRSSReader.PostTags.NAME, tag);
					this.getContentResolver().insert(SzRSSReader.PostTags.CONTENT_URI, value);
				}
			}
			else
			{
				PostTagViewTag viewtag = (PostTagViewTag)view.getTag();
				if(!viewtag.is_new)
				{
					String where = SzRSSReader.PostTags.TAG_ID + "='" + viewtag._id + "' AND "
					+ SzRSSReader.PostTags.POST_ID + "='" + mPostID + "'";
					this.getContentResolver().delete(SzRSSReader.PostTags.CONTENT_URI, where, null);
				}
			}
		}
	}
	
	private void initTagView()
	{
		Uri uri = ContentUris.withAppendedId(SzRSSReader.PostTags.CONTENT_URI, mPostID);
		String[] cols = new String[]{SzRSSReader.PostTags._ID, SzRSSReader.PostTags.NAME,
				SzRSSReader.PostTags.TAG_ID};
		Cursor c = this.managedQuery(uri, cols, null, null, null);
		
		if(c.getCount() > 0)
		{
			c.moveToFirst();
			do
			{
				View view = mInflater.inflate(R.layout.edit_contact_entry, mTagGroup, false);
				View deletebtn = view.findViewById(R.id.delete);
				
				TextView commenttext = (TextView)view.findViewById(R.id.comment_data);
				AutoCompleteTextView tagView = (AutoCompleteTextView)view.findViewById(R.id.tag_data);

				tagView.setVisibility(View.VISIBLE);
				commenttext.setVisibility(View.GONE);
				
				tagView.setText(c.getString(c.getColumnIndexOrThrow(SzRSSReader.PostTags.NAME)));
				tagView.setAdapter(mAdapter);
				deletebtn.setOnClickListener(this);
				
				PostTagViewTag viewtag = new PostTagViewTag();
				viewtag.is_new = false;
				viewtag.old_text = tagView.getText().toString();
				viewtag._id = c.getLong(c.getColumnIndexOrThrow(SzRSSReader.PostTags.TAG_ID));
				
				view.setTag(viewtag);
				
				mTagViewList.add(view);
				
			}while(c.moveToNext());
		}
		
		c.close();
		
		View view = mInflater.inflate(R.layout.edit_contact_entry, mTagGroup, false);
		View deletebtn = view.findViewById(R.id.delete);
		
		TextView commenttext = (TextView)view.findViewById(R.id.comment_data);
		AutoCompleteTextView tagView = (AutoCompleteTextView)view.findViewById(R.id.tag_data);

		tagView.setVisibility(View.VISIBLE);
		commenttext.setVisibility(View.GONE);
		tagView.setAdapter(mAdapter);
		deletebtn.setOnClickListener(this);
		
		PostTagViewTag viewtag = new PostTagViewTag();
		viewtag.is_new = true;
		
		view.setTag(viewtag);
		mTagViewList.add(view);
		
		buildView();
	}
	
	private void initCommentView()
	{
		Uri uri = SzRSSReader.PostComments.CONTENT_URI;
		
		String[] cols = new String[]{SzRSSReader.PostComments._ID, SzRSSReader.PostComments.COMMENT};
		String where = SzRSSReader.PostComments.POST_ID + "='" + mPostID + "'";
		
		Cursor c = this.managedQuery(uri, cols, where, null, null);
		
		if(c.getCount() > 0)
		{
			c.moveToFirst();
			do
			{
				View view = mInflater.inflate(R.layout.edit_contact_entry, mTagGroup, false);
				View deletebtn = view.findViewById(R.id.delete);
				
				TextView commenttext = (TextView)view.findViewById(R.id.comment_data);
				AutoCompleteTextView tagView = (AutoCompleteTextView)view.findViewById(R.id.tag_data);

				tagView.setVisibility(View.GONE);
				commenttext.setVisibility(View.VISIBLE);
				
				commenttext.setText(c.getString(c.getColumnIndexOrThrow(SzRSSReader.PostComments.COMMENT)));
				deletebtn.setOnClickListener(this);
				
				PostTagViewTag viewtag = new PostTagViewTag();
				viewtag.is_new = false;
				viewtag.old_text = commenttext.getText().toString();
				viewtag._id = c.getLong(c.getColumnIndexOrThrow(SzRSSReader.PostComments._ID));
				
				view.setTag(viewtag);
				
				mTagViewList.add(view);
				
			}while(c.moveToNext());
		}
		
		c.close();
		
		View view = mInflater.inflate(R.layout.edit_contact_entry, mTagGroup, false);
		View deletebtn = view.findViewById(R.id.delete);
		
		TextView commenttext = (TextView)view.findViewById(R.id.comment_data);
		AutoCompleteTextView tagView = (AutoCompleteTextView)view.findViewById(R.id.tag_data);

		tagView.setVisibility(View.GONE);
		commenttext.setVisibility(View.VISIBLE);
		
		deletebtn.setOnClickListener(this);
		
		PostTagViewTag viewtag = new PostTagViewTag();
		viewtag.is_new = true;
		
		view.setTag(viewtag);
		mTagViewList.add(view);
		
		buildView();
	}
	
	
	private void clearDeleteView()
	{

		for(int i = mTagViewList.size(); i > 0 ; i --)
		{
			if(mTagViewList.get(i - 1).getVisibility() == View.GONE)
			{
				mTagViewList.remove(i - 1);
			}
		}
		
		mDeleteViewNum = 0;
	}
	
	private void buildView()
	{

		mTagGroup.removeAllViews();
		for(int i =0; i < mTagViewList.size(); i++)
		{
			mTagGroup.addView(mTagViewList.get(i));
		}
		
	}
	
	public static class ContactListAdapter extends CursorAdapter implements Filterable {
        public ContactListAdapter(Context context, Cursor c) {
            super(context, c);
            mContent = context.getContentResolver();
        }

        @Override
        public View newView(Context context, Cursor cursor, ViewGroup parent) {
            final LayoutInflater inflater = LayoutInflater.from(context);
            final TextView view = (TextView) inflater.inflate(
                    android.R.layout.simple_dropdown_item_1line, parent, false);
            view.setText(cursor.getString(1));
            return view;
        }

        @Override
        public void bindView(View view, Context context, Cursor cursor) {
            ((TextView) view).setText(cursor.getString(1));
        }

        @Override
        public String convertToString(Cursor cursor) {
            return cursor.getString(1);
        }

        @Override
        public Cursor runQueryOnBackgroundThread(CharSequence constraint) {
            if (getFilterQueryProvider() != null) {
                return getFilterQueryProvider().runQuery(constraint);
            }

            StringBuilder buffer = null;
            String[] args = null;
            if (constraint != null) {
                buffer = new StringBuilder();
                buffer.append("UPPER(");
                buffer.append(SzRSSReader.Tags.NAME);
                buffer.append(") GLOB ?");
                args = new String[] { constraint.toString().toUpperCase() + "*" };
            }

            return mContent.query(SzRSSReader.Tags.CONTENT_URI, TAG_PROJECTION,
                    buffer == null ? null : buffer.toString(), args,
                    		SzRSSReader.Tags.DEFAULT_SORT_ORDER);
        }

        private ContentResolver mContent;        
    }

    private static final String[] TAG_PROJECTION = new String[] {
        SzRSSReader.Tags._ID,
        SzRSSReader.Tags.NAME
    };
}


class PostTagViewTag
{
	public boolean is_new;
	public String old_text;
	public long _id;
}